package com.hu.network.http.bodyImpl;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import okio.Source;

/**
 * 说明：
 *
 * @author ： hucanhua
 * @date ： 2017/10/28
 */
public class ResponseBodyImpl extends ResponseBody {
    private ProgressListener progressListener;
    private final ResponseBody responseBody;
    private BufferedSource bufferedSource;

    public ResponseBodyImpl(ResponseBody responseBody, ProgressListener progressListener) {
        super();
        this.responseBody = responseBody;
        this.progressListener = progressListener;
    }

    @Nullable
    @Override
    public MediaType contentType() {
        return this.responseBody.contentType();
    }

    @Override
    public long contentLength() {
        return this.responseBody.contentLength();
    }

    @Override
    public BufferedSource source() {
        if (this.bufferedSource == null) {
            this.bufferedSource = Okio.buffer(this.source(this.responseBody.source()));
        }
        return this.bufferedSource;
    }

    private Source source(Source source) {
        return new ForwardingSource(source) {
            long totalBytesRead = 0L;

            @Override
            public long read(@NonNull Buffer sink, long byteCount) throws IOException {
                long bytesRead = super.read(sink, byteCount);
                this.totalBytesRead += bytesRead != -1L ? bytesRead : 0L;
                if (progressListener != null) {
                    progressListener.progress(totalBytesRead, responseBody.contentLength(),bytesRead == -1L);
                }
                return bytesRead;
            }
        };
    }

    public interface ProgressListener {
        void progress(long bytesRead, long contentLength, boolean done);
    }
}
